<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>camera</title>
</head>

<body>
  <div id="contentHolder">
    <video id="video" autoplay style="background-color: #000"></video>
    <canvas id="canvas" style="display: none;"></canvas>
    <img id="imgXX" src="" />
  </div>
  <button id="btn_snap" onclick="takePhoto()">拍照</button>
  <script>
    const cvs = document.getElementById('canvas')
    const video = document.getElementById('video')
    cvs.width = cvs.height = video.width = video.height = 400
    const { width, height } = cvs
    const ctx = cvs.getContext('2d')

    const constraints = {
      video: {
        width,
        height
      }
    }
    navigator.mediaDevices.getUserMedia(constraints).then(stream => {
      video.srcObject = stream
      video.onloadedmetadata = () => video.play()
    })
    function takePhoto() {
      ctx.drawImage(video, 0, 0, width, height)
      document.getElementById('imgXX').src = canvas.toDataURL('image/png')
    }

  </script>
</body>

</html>